/**
 * 通用API管理工具
 * 提供统一的API调用接口和错误处理
 */

import { request } from '@/utils/request'
import type { PageResponse } from '@/types/api'

// 通用查询参数
export interface CommonQueryParams {
  pageNum?: number
  pageSize?: number
  [key: string]: unknown
}

// 文件上传参数
export interface FileUploadParams {
  file: File
  folder?: string
}

// 文件下载参数
export interface FileDownloadParams {
  url: string
  filename?: string
  params?: Record<string, unknown>
}

// 通用CRUD操作工具
export const crudApi = {
  // 获取分页列表
  getPageList: <T>(url: string, params: CommonQueryParams): Promise<PageResponse<T>> => {
    return request.post(url, params)
  },

  // 获取列表
  getList: <T>(url: string, params?: Record<string, unknown>): Promise<T[]> => {
    return request.get(url, params)
  },

  // 获取详情
  getDetail: <T>(url: string, id: string | number): Promise<T> => {
    return request.get(`${url}/${id}`)
  },

  // 新增
  create: <T>(url: string, data: unknown): Promise<T> => {
    return request.post(url, data)
  },

  // 更新
  update: <T>(url: string, data: unknown): Promise<T> => {
    return request.put(url, data)
  },

  // 删除
  delete: (url: string, ids: (string | number)[]): Promise<void> => {
    return request.delete(url, { ids })
  },

  // 批量操作
  batchOperation: (url: string, data: unknown): Promise<void> => {
    return request.post(url, data)
  }
}

// 文件操作工具
export const fileApi = {
  // 上传文件
  upload: (params: FileUploadParams): Promise<{ url: string }> => {
    return request.upload('/common/upload', params.file)
  },

  // 下载文件
  download: (params: FileDownloadParams): Promise<void> => {
    return request.download(params.url, params.params, params.filename)
  },

  // 预览文件
  preview: (url: string): string => {
    return `${import.meta.env.VITE_API_BASE_URL || ''}${url}`
  }
}

// 系统信息工具
export const systemApi = {
  // 获取系统信息
  getInfo: () => {
    return request.get('/system/info')
  },

  // 获取系统配置
  getConfig: () => {
    return request.get('/system/config')
  },

  // 更新系统配置
  updateConfig: (data: unknown) => {
    return request.put('/system/config', data)
  }
}

// 认证相关工具
export const authApi = {
  // 获取验证码
  getCaptcha: () => {
    return request.get('/auth/captcha')
  },

  // 刷新Token
  refreshToken: () => {
    return request.post('/auth/refresh')
  }
}

// 模板相关工具
export const templateApi = {
  // 下载导入模板
  downloadImportTemplate: (baseUrl: string, filename: string) => {
    return fileApi.download({ 
      url: `${baseUrl}/importTemplate`, 
      filename 
    })
  },

  // 导出数据
  exportData: (baseUrl: string, params: Record<string, unknown>, filename: string) => {
    return fileApi.download({ 
      url: `${baseUrl}/export`, 
      params, 
      filename 
    })
  }
}

// 导出所有工具
export default {
  crudApi,
  fileApi,
  systemApi,
  authApi,
  templateApi
}
